import React, { Component } from 'react'
import { connect } from 'react-redux'
import { actions } from '../store/cart'
import { bindActionCreators } from 'redux'

class CartItem extends Component {
    changeCountFn = (info) => this.props.changeCount(info)
    inputCountFn = (info,e) => {
        const num = Number(e.target.value)
        if (num < 1) info.num = 1;
        else info.num = num;
        this.props.inputCount(info)
    }
    render() {
        const { itemData:{id, price, name, pic, count} } = this.props
        return (
            <div className='cart-item'>
                <img className='shop-img' src={pic}/>
                <div className='right'>
                    <div className='name'>{name}</div>
                    <div className='price-box'>
                        <div className='price'>￥{price}</div>
                        <div className='count'>
                            <button onClick={() => this.changeCountFn({id, num: -1})}>-</button>
                            <input type='number' value={count} onChange={(e) => this.inputCountFn({id},e)}/>
                            <button onClick={() => this.changeCountFn({id, num: 1})}>+</button>
                        </div>
                    </div>
                </div>
            </div>
        )
    }
}

function mapStateFromProps (state) {
    // 获取 store state 中所有数据，并转成当前组件的 props
    return state.cartStore  // 只分发 cartStore
}
  
function mapDispatchFromProps (dispatch) {
    // 发送 actions 中的 action
    // 将 actions 中的方法绑定在组件身上，转成 props
    return bindActionCreators(actions, dispatch)
}

export default connect(mapStateFromProps,mapDispatchFromProps)(CartItem)
